/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package views;

import entities.Clientes;
import entities.Logs;
import entities.Usuarios;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.persistence.Query;
import javax.persistence.RollbackException;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import logica.ExcelJTableExporter;
import logica.correoElectronico;

/**
 *
 * @author Smuggler
 */
public class AltaClientes extends JPanel {

    private Logs logs;
    public static JFrame frame;
    private boolean desdeReserva = false;
    private boolean editando = false;
    private boolean estadocorreo = false;
    private Usuarios usuario;
    entities.Clientes c;
    private String tipoBusqueda;

    public AltaClientes(JFrame frame, boolean activoNew, Usuarios usuario) {
        initComponents();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.frame = frame;
        desdeReserva = activoNew;
        if (activoNew) {
            nuevoButtonActionPerformed(null);
        }
        buttonGroup1.add(siRadioButton);
        buttonGroup1.add(noRadioButton);
        buttonGroup1.add(todosRadioButton);
        this.usuario = usuario;
    }

    public JFrame getFrame() {
        return frame;
    }

    private Integer getIDCliente(String documento, String procedencia) {
        Query queryIDCliente;
        Clientes cli;
        queryIDCliente = entityManager.createNamedQuery("Clientes.findByDocumentoProcedencia");
        queryIDCliente.setParameter("documento", documento);
        queryIDCliente.setParameter("procedencia", procedencia);
        cli = (Clientes) queryIDCliente.getSingleResult();
        return cli.getIdCliente();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("SIAATPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT c FROM Clientes c WHERE c.idCliente != '1' ORDER BY c.apellido ASC,c.nombres ASC");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        buttonGroup1 = new javax.swing.ButtonGroup();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        apellidoLabel = new javax.swing.JLabel();
        nombresLabel = new javax.swing.JLabel();
        procedenciaLabel = new javax.swing.JLabel();
        telefonoLabel = new javax.swing.JLabel();
        celularLabel = new javax.swing.JLabel();
        vehiculoLabel = new javax.swing.JLabel();
        patenteLabel = new javax.swing.JLabel();
        emailLabel = new javax.swing.JLabel();
        extranjeroLabel = new javax.swing.JLabel();
        observacionesLabel = new javax.swing.JLabel();
        apellidoField = new javax.swing.JTextField();
        nombresField = new javax.swing.JTextField();
        procedenciaField = new javax.swing.JTextField();
        telefonoField = new javax.swing.JTextField();
        celularField = new javax.swing.JTextField();
        patenteField = new javax.swing.JTextField();
        emailField = new javax.swing.JTextField();
        guardarButton = new javax.swing.JButton();
        cancelarButton = new javax.swing.JButton();
        nuevoButton = new javax.swing.JButton();
        extranjeroComboBox = new javax.swing.JComboBox();
        vehiculoComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        observacionesField = new javax.swing.JTextArea();
        ayudaLabel1 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        buscarClienteLabel = new javax.swing.JLabel();
        textoBusquedaField = new javax.swing.JTextField();
        buscarButton = new javax.swing.JButton();
        cancelarBusquedaButton = new javax.swing.JButton();
        documentoLabel = new javax.swing.JLabel();
        documentoTextField = new javax.swing.JTextField();
        exportarExcelButton = new javax.swing.JButton();
        activoLabel = new javax.swing.JLabel();
        activoComboBox = new javax.swing.JComboBox();
        siRadioButton = new javax.swing.JRadioButton();
        noRadioButton = new javax.swing.JRadioButton();
        todosRadioButton = new javax.swing.JRadioButton();

        FormListener formListener = new FormListener();

        masterTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${apellido}"));
        columnBinding.setColumnName("Apellido");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${nombres}"));
        columnBinding.setColumnName("Nombres");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${documento}"));
        columnBinding.setColumnName("Documento");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${procedencia}"));
        columnBinding.setColumnName("Procedencia");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${telefono}"));
        columnBinding.setColumnName("Telefono");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${celular}"));
        columnBinding.setColumnName("Celular");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${vehiculo}"));
        columnBinding.setColumnName("Vehiculo");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${patente}"));
        columnBinding.setColumnName("Patente");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${email}"));
        columnBinding.setColumnName("Email");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${extranjero}"));
        columnBinding.setColumnName("Extranjero");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${observaciones}"));
        columnBinding.setColumnName("Observaciones");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${activo}"));
        columnBinding.setColumnName("Activo");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(3).setResizable(false);
        masterTable.getColumnModel().getColumn(4).setResizable(false);
        masterTable.getColumnModel().getColumn(5).setResizable(false);
        masterTable.getColumnModel().getColumn(6).setResizable(false);
        masterTable.getColumnModel().getColumn(7).setResizable(false);
        masterTable.getColumnModel().getColumn(8).setResizable(false);
        masterTable.getColumnModel().getColumn(9).setResizable(false);
        masterTable.getColumnModel().getColumn(10).setResizable(false);

        apellidoLabel.setText("Apellido:");

        nombresLabel.setText("Nombres:");

        procedenciaLabel.setText("Procedencia:");

        telefonoLabel.setText("Telefono:");

        celularLabel.setText("Celular:");

        vehiculoLabel.setText("Vehiculo:");

        patenteLabel.setText("Patente:");

        emailLabel.setText("E-mail:");

        extranjeroLabel.setText("Extranjero:");

        observacionesLabel.setText("Observaciones:");

        apellidoField.setEnabled(false);

        nombresField.setEnabled(false);

        procedenciaField.setEnabled(false);

        telefonoField.setEnabled(false);

        celularField.setEnabled(false);

        patenteField.setEnabled(false);

        emailField.setEnabled(false);
        emailField.addFocusListener(formListener);

        guardarButton.setBackground(new java.awt.Color(1, 154, 210));
        guardarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        guardarButton.setForeground(new java.awt.Color(255, 255, 255));
        guardarButton.setText("Guardar");
        guardarButton.setEnabled(false);
        guardarButton.addActionListener(formListener);

        cancelarButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarButton.setText("Cancelar");
        cancelarButton.setEnabled(false);
        cancelarButton.addActionListener(formListener);

        nuevoButton.setBackground(new java.awt.Color(1, 154, 210));
        nuevoButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        nuevoButton.setForeground(new java.awt.Color(255, 255, 255));
        nuevoButton.setText("Nuevo");
        nuevoButton.addActionListener(formListener);

        extranjeroComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NO", "SI" }));
        extranjeroComboBox.setSelectedIndex(-1);
        extranjeroComboBox.setEnabled(false);

        vehiculoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "NO", "SI" }));
        vehiculoComboBox.setSelectedIndex(-1);
        vehiculoComboBox.setEnabled(false);

        observacionesField.setColumns(20);
        observacionesField.setRows(5);
        observacionesField.setEnabled(false);
        jScrollPane1.setViewportView(observacionesField);

        ayudaLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/help.png"))); // NOI18N
        ayudaLabel1.addMouseListener(formListener);

        buscarClienteLabel.setText("Buscar Cliente:");

        textoBusquedaField.addKeyListener(formListener);

        buscarButton.setBackground(new java.awt.Color(1, 154, 210));
        buscarButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        buscarButton.setForeground(new java.awt.Color(255, 255, 255));
        buscarButton.setText("Buscar");
        buscarButton.addActionListener(formListener);

        cancelarBusquedaButton.setBackground(new java.awt.Color(1, 154, 210));
        cancelarBusquedaButton.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        cancelarBusquedaButton.setForeground(new java.awt.Color(255, 255, 255));
        cancelarBusquedaButton.setText("Cancelar Busqueda");
        cancelarBusquedaButton.addActionListener(formListener);

        documentoLabel.setText("Documento:");

        documentoTextField.setEnabled(false);

        exportarExcelButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/xls.png"))); // NOI18N
        exportarExcelButton.setText("Exportar");
        exportarExcelButton.addActionListener(formListener);

        activoLabel.setText("Activo:");

        activoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "SI", "NO" }));
        activoComboBox.setEnabled(false);

        siRadioButton.setText("SI");
        siRadioButton.addActionListener(formListener);

        noRadioButton.setText("NO");
        noRadioButton.addActionListener(formListener);

        todosRadioButton.setSelected(true);
        todosRadioButton.setText("TODOS");
        todosRadioButton.addActionListener(formListener);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.TRAILING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(masterScrollPane)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(ayudaLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(exportarExcelButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(nuevoButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(guardarButton))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(observacionesLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(apellidoLabel)
                            .addComponent(nombresLabel)
                            .addComponent(procedenciaLabel)
                            .addComponent(documentoLabel))
                        .addGap(17, 17, 17)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(documentoTextField)
                            .addComponent(apellidoField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 338, Short.MAX_VALUE)
                            .addComponent(nombresField, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(procedenciaField))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(activoLabel)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(celularLabel, javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(telefonoLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addComponent(emailLabel, javax.swing.GroupLayout.Alignment.TRAILING)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(telefonoField, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                            .addComponent(celularField)
                            .addComponent(emailField)
                            .addComponent(activoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(vehiculoLabel)
                                .addGap(17, 17, 17)
                                .addComponent(vehiculoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(patenteLabel)
                                .addGap(18, 18, 18)
                                .addComponent(patenteField, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(extranjeroLabel)
                                .addGap(18, 18, 18)
                                .addComponent(extranjeroComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(siRadioButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(noRadioButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(todosRadioButton)
                                .addGap(31, 31, 31)
                                .addComponent(buscarClienteLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(textoBusquedaField, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(buscarButton)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(cancelarBusquedaButton)))))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {cancelarButton, guardarButton, nuevoButton});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(apellidoLabel)
                            .addComponent(apellidoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(nombresLabel)
                            .addComponent(nombresField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(telefonoLabel)
                            .addComponent(telefonoField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(celularLabel)
                            .addComponent(celularField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(emailField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(emailLabel))
                    .addComponent(procedenciaLabel)
                    .addComponent(procedenciaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(documentoLabel)
                    .addComponent(documentoTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(activoLabel)
                    .addComponent(activoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(vehiculoLabel)
                    .addComponent(vehiculoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(patenteLabel)
                    .addComponent(patenteField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(extranjeroLabel)
                    .addComponent(extranjeroComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(observacionesLabel)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(buscarClienteLabel)
                            .addComponent(textoBusquedaField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(buscarButton)
                            .addComponent(cancelarBusquedaButton)
                            .addComponent(siRadioButton)
                            .addComponent(noRadioButton)
                            .addComponent(todosRadioButton))
                        .addGap(18, 18, 18)
                        .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(ayudaLabel1, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(guardarButton)
                                .addComponent(cancelarButton)
                                .addComponent(nuevoButton))))
                    .addComponent(exportarExcelButton))
                .addContainerGap())
        );

        bindingGroup.bind();
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.FocusListener, java.awt.event.KeyListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == guardarButton) {
                AltaClientes.this.guardarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarButton) {
                AltaClientes.this.cancelarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == nuevoButton) {
                AltaClientes.this.nuevoButtonActionPerformed(evt);
            }
            else if (evt.getSource() == buscarButton) {
                AltaClientes.this.buscarButtonActionPerformed(evt);
            }
            else if (evt.getSource() == cancelarBusquedaButton) {
                AltaClientes.this.cancelarBusquedaButtonActionPerformed(evt);
            }
            else if (evt.getSource() == exportarExcelButton) {
                AltaClientes.this.exportarExcelButtonActionPerformed(evt);
            }
            else if (evt.getSource() == siRadioButton) {
                AltaClientes.this.siRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == noRadioButton) {
                AltaClientes.this.noRadioButtonActionPerformed(evt);
            }
            else if (evt.getSource() == todosRadioButton) {
                AltaClientes.this.todosRadioButtonActionPerformed(evt);
            }
        }

        public void focusGained(java.awt.event.FocusEvent evt) {
        }

        public void focusLost(java.awt.event.FocusEvent evt) {
            if (evt.getSource() == emailField) {
                AltaClientes.this.emailFieldFocusLost(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == textoBusquedaField) {
                AltaClientes.this.textoBusquedaFieldKeyPressed(evt);
            }
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == masterTable) {
                AltaClientes.this.masterTableMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == ayudaLabel1) {
                AltaClientes.this.ayudaLabel1MouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
    private void cancelarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarButtonActionPerformed
        refrescar();
    }//GEN-LAST:event_cancelarButtonActionPerformed
    private void refrescar() {
        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        habilitarBotones(false);
        limpiarBotones();
        habilitarBotonesBusqueda(true);
    }

    private void habilitarBotones(boolean estado) {
        nuevoButton.setEnabled(!estado);
        masterTable.setEnabled(!estado);
        cancelarButton.setEnabled(estado);
        guardarButton.setEnabled(estado);
        apellidoField.setEnabled(estado);
        nombresField.setEnabled(estado);
        procedenciaField.setEnabled(estado);
        telefonoField.setEnabled(estado);
        celularField.setEnabled(estado);
        vehiculoComboBox.setEnabled(estado);
        patenteField.setEnabled(estado);
        emailField.setEnabled(estado);
        extranjeroComboBox.setEnabled(estado);
        observacionesField.setEnabled(estado);
        documentoTextField.setEnabled(estado);
        activoComboBox.setEnabled(estado);
    }

    private void habilitarBotonesBusqueda(boolean estado) {
        textoBusquedaField.setEnabled(estado);
        siRadioButton.setEnabled(estado);
        noRadioButton.setEnabled(estado);
        todosRadioButton.setEnabled(estado);
        buscarButton.setEnabled(estado);
        cancelarBusquedaButton.setEnabled(estado);
        buscarClienteLabel.setEnabled(estado);

    }

    private void limpiarBotones() {
        apellidoField.setText("");
        nombresField.setText("");
        procedenciaField.setText("");
        telefonoField.setText("");
        celularField.setText("");
        vehiculoComboBox.setSelectedIndex(-1);
        patenteField.setText("");
        emailField.setText("");
        extranjeroComboBox.setSelectedIndex(-1);
        observacionesField.setText("");

        documentoTextField.setText("");
        activoComboBox.setSelectedIndex(0);
    }

    private void nuevoButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevoButtonActionPerformed
        habilitarBotones(true);
        habilitarBotonesBusqueda(false);
    }//GEN-LAST:event_nuevoButtonActionPerformed
    private void nuevoCliente() {
        c = new entities.Clientes();
        logs = new Logs();
        logs.setUsuario(usuario);
        entityManager.persist(c);
        list.add(c);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 0, true));


    }

    private boolean existeCliente(String documento) {
        int fila = 0;
        Query queryExisteCliente = entityManager.createNamedQuery("Clientes.findByDocumentoCount");
        queryExisteCliente.setParameter("documento", documento);

        int count = ((Long) queryExisteCliente.getSingleResult()).intValue();
        if ((count > 0)) {
            for (Clientes clientes : list) {
                if (masterTable.getSelectedRow() == fila) {
                } else {
                    if (clientes.getDocumento().equals(documento)) {

                        return true;

                    }

                }
                fila++;
            }

        }

        return false;
    }
    private void guardarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_guardarButtonActionPerformed
        emailFieldFocusLost(null);

        if (!estadocorreo || "".equals(apellidoField.getText()) || vehiculoComboBox.getSelectedIndex() < 0 || extranjeroComboBox.getSelectedIndex() < 0 || "".equals(documentoTextField.getText())) {
            String guardarmensaje = "";
            if ("".equals(apellidoField.getText())) {
                guardarmensaje = guardarmensaje + "                     Apellido\n";
            }
            if ("".equals(documentoTextField.getText())) {
                guardarmensaje = guardarmensaje + "                     Documento\n";
            }
            if (vehiculoComboBox.getSelectedIndex() < 0) {
                guardarmensaje = guardarmensaje + "                     Vehiculo:\n";
            }
            if (extranjeroComboBox.getSelectedIndex() < 0) {
                guardarmensaje = guardarmensaje + "                     Extranjero:\n";
            }
            if (!estadocorreo) {
                guardarmensaje = guardarmensaje + "                     E-mail:\n";
            }
            JOptionPane.showMessageDialog(this, "Revise el/los siguientes campos:\n" + guardarmensaje, "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        } else {
            if (!existeCliente(documentoTextField.getText())) {
                try {
                    if (!editando) {
                        nuevoCliente();
                    }
                    logs = new Logs();
                    logs.setUsuario(usuario);
                    c.setApellido(apellidoField.getText());
                    c.setNombres(nombresField.getText());
                    c.setProcedencia(procedenciaField.getText());
                    c.setDocumento(documentoTextField.getText());
                    c.setTelefono(telefonoField.getText());
                    c.setCelular(celularField.getText());
                    c.setEmail(emailField.getText());
                    c.setVehiculo(vehiculoComboBox.getSelectedItem().toString());
                    c.setPatente(patenteField.getText());
                    c.setExtranjero(extranjeroComboBox.getSelectedItem().toString());
                    c.setObservaciones(observacionesField.getText());
                    c.setActivo(activoComboBox.getSelectedItem().toString());
                    if (c.getIdCliente() == null) {
                        entityManager.getTransaction().commit();
                        entityManager.getTransaction().begin();
                        Integer idCliente = getIDCliente(c.getDocumento(), c.getProcedencia());
                        logs.setearObservaciones("Alta", "Clientes", idCliente, "AltaClientes");
                    } else {
                        logs.setearObservaciones("Modificación", "Clientes", c.getIdCliente(), "AltaClientes");
                    }
                    entityManager.persist(logs);
                    entityManager.getTransaction().commit();
                    entityManager.getTransaction().begin();
                } catch (RollbackException rex) {
                    rex.printStackTrace();
                    entityManager.getTransaction().begin();
                    List<entities.Clientes> merged = new ArrayList<entities.Clientes>(list.size());
                    for (entities.Clientes c : list) {
                        merged.add(entityManager.merge(c));
                    }
                    list.clear();
                    list.addAll(merged);
                }
                habilitarBotones(false);

                if (desdeReserva) {
                    try {
                        AltaReservas.setearCliente(c);
                        this.frame.dispose();   // cerrar la ventana
                    } catch (Exception e) {
                        // No cierro la ventana porque el dialogo fue abierto directamente
                    }
                }
                refrescar();

            } else {
                JOptionPane.showMessageDialog(this, "El Documento ya se encuentra registrado", "Atención", JOptionPane.ERROR_MESSAGE, null);
            }
        }


    }//GEN-LAST:event_guardarButtonActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        habilitarBotones(true);
        habilitarBotonesBusqueda(false);
        estadocorreo = true;
        editando = true;
        c = list.get(masterTable.getSelectedRow());
        apellidoField.setText(c.getApellido());
        nombresField.setText(c.getNombres());
        telefonoField.setText(c.getTelefono());
        celularField.setText(c.getCelular());
        procedenciaField.setText(c.getProcedencia());
        emailField.setText(c.getEmail());
        documentoTextField.setText(c.getDocumento());
        vehiculoComboBox.setSelectedItem(c.getVehiculo());
        patenteField.setText(c.getPatente());
        extranjeroComboBox.setSelectedItem(c.getExtranjero());
        observacionesField.setText(c.getObservaciones());
        activoComboBox.setSelectedItem(c.getActivo());


    }//GEN-LAST:event_masterTableMouseClicked

    private void emailFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_emailFieldFocusLost

        String emailAddress = emailField.getText().toLowerCase();
        emailAddress = emailAddress.replaceAll(" ", "");
        emailField.setText(emailAddress);
        correoElectronico.getcorreoElectronico(emailAddress);


        if (correoElectronico.getcorreoElectronico(emailAddress) || ("".equals(emailField.getText()))) {

            estadocorreo = true;
        } else {
            estadocorreo = false;
        }
    }//GEN-LAST:event_emailFieldFocusLost

    private void ayudaLabel1MouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_ayudaLabel1MouseEntered
        ayudaLabel1.setToolTipText("En esta pantalla usted podra agregar,\n editar y eliminar clientes");
    }//GEN-LAST:event_ayudaLabel1MouseEntered

    private void buscarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buscarButtonActionPerformed
        Query query2;

        if (todosRadioButton.isSelected()) {
            query2 = entityManager.createNamedQuery("Clientes.findByTexto").setParameter("texto", textoBusquedaField.getText()).setParameter("activo", "SI").setParameter("activo2", "NO");

        } else {
            query2 = entityManager.createNamedQuery("Clientes.findByTexto").setParameter("texto", textoBusquedaField.getText()).setParameter("activo", tipoBusqueda).setParameter("activo2", "");

        }





        List<Clientes> listaAux = new ArrayList<Clientes>();

        list.clear();
        listaAux = query2.getResultList();
        list.addAll(listaAux);
        if (list.isEmpty()) {
            JOptionPane.showMessageDialog(this, "No se encontro ningun resultado, revise los campos de busqueda", "Atención", JOptionPane.INFORMATION_MESSAGE, null);
        }

    }//GEN-LAST:event_buscarButtonActionPerformed

    private void cancelarBusquedaButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarBusquedaButtonActionPerformed
        textoBusquedaField.setText("");
        cancelarButtonActionPerformed(null);
    }//GEN-LAST:event_cancelarBusquedaButtonActionPerformed

    private void textoBusquedaFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textoBusquedaFieldKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            buscarButtonActionPerformed(null);
        }
    }//GEN-LAST:event_textoBusquedaFieldKeyPressed

    private void exportarExcelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exportarExcelButtonActionPerformed
        //ExcelTableExporter exportador = new ExcelTableExporter();
        //exportador.toExcel(masterTable);
        new ExcelJTableExporter(masterTable, "Clientes").export();
    }//GEN-LAST:event_exportarExcelButtonActionPerformed

    private void siRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_siRadioButtonActionPerformed
        tipoBusqueda = "SI";       // TODO add your handling code here:
    }//GEN-LAST:event_siRadioButtonActionPerformed

    private void noRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_noRadioButtonActionPerformed
        tipoBusqueda = "NO";       // TODO add your handling code here:
    }//GEN-LAST:event_noRadioButtonActionPerformed

    private void todosRadioButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_todosRadioButtonActionPerformed
        tipoBusqueda = "";       // TODO add your handling code here:
    }//GEN-LAST:event_todosRadioButtonActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox activoComboBox;
    private javax.swing.JLabel activoLabel;
    private javax.swing.JTextField apellidoField;
    private javax.swing.JLabel apellidoLabel;
    private javax.swing.JLabel ayudaLabel1;
    private javax.swing.JButton buscarButton;
    private javax.swing.JLabel buscarClienteLabel;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JButton cancelarBusquedaButton;
    private javax.swing.JButton cancelarButton;
    private javax.swing.JTextField celularField;
    private javax.swing.JLabel celularLabel;
    private javax.swing.JLabel documentoLabel;
    private javax.swing.JTextField documentoTextField;
    private javax.swing.JTextField emailField;
    private javax.swing.JLabel emailLabel;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JButton exportarExcelButton;
    private javax.swing.JComboBox extranjeroComboBox;
    private javax.swing.JLabel extranjeroLabel;
    private javax.swing.JButton guardarButton;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private java.util.List<entities.Clientes> list;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JRadioButton noRadioButton;
    private javax.swing.JTextField nombresField;
    private javax.swing.JLabel nombresLabel;
    private javax.swing.JButton nuevoButton;
    private javax.swing.JTextArea observacionesField;
    private javax.swing.JLabel observacionesLabel;
    private javax.swing.JTextField patenteField;
    private javax.swing.JLabel patenteLabel;
    private javax.swing.JTextField procedenciaField;
    private javax.swing.JLabel procedenciaLabel;
    private javax.persistence.Query query;
    private javax.swing.JRadioButton siRadioButton;
    private javax.swing.JTextField telefonoField;
    private javax.swing.JLabel telefonoLabel;
    private javax.swing.JTextField textoBusquedaField;
    private javax.swing.JRadioButton todosRadioButton;
    private javax.swing.JComboBox vehiculoComboBox;
    private javax.swing.JLabel vehiculoLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(boolean activo, Usuarios user) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(AltaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AltaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AltaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AltaClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        final boolean activoNew = activo;
        final Usuarios usuario = user;
        /*
         * Create and display the form
         */
        AltaClientes.frame = new JFrame();
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                frame.setContentPane(new AltaClientes(frame, activoNew, usuario));
                frame.pack();
                frame.setVisible(true);
                frame.setTitle("Administracion   -   Clientes   -   Sistema Integrado de Administración de Alquileres Turísticos  ");
                frame.setIconImage(new ImageIcon(getClass().getResource("/images/logo.png")).getImage());
                frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                frame.addWindowListener(new WindowAdapter() {

                    public void windowClosing(WindowEvent e) {
                        if (frame != null) {
                            frame.setVisible(false);
                        }
                        frame = null;
                    }
                });
            }
        });
    }
}
